import Vue from 'vue'
	import { alluser,adduser,userinfo } from '@/request/app.js'
import Vuex from 'vuex'
import websocketManager from '@/websocketService.js';
import { logs } from '@/request/setarticle.js'
import createPersistedState from 'vuex-persistedstate'
import uploadurl from "@/config/index.js"
Vue.use(Vuex)
		import { verifytoken,Renewaltoken} from '@/request/app.js'
const store = new Vuex.Store({
	state: {
		nowchagemess:'',//最新获取的数据
		chatList: [],
		chatItem: '',
		id:'',
		imageurl: '',
		nickname: '',
		fansnum: '',
		intro: '',
		username: '',
		follownum: '',
		followlist:'[]',
		fanslist:'[]',
		followwarn:'',
		concernnum:'',
		token:'',
		 tokenCheckIntervalId: null, // 用于存储定时器ID
		 // 被提醒信息的角标数
		 messagenum:0,
		//公共的变量，这里的变量不能随便修改，只能通过触发mutations的方法才能改变
	},
	mutations: {
		setnowchagemess(state, item) {
		     state.nowchagemess = item;
		   },
		setmessagenum(state, messagenum) {
		     state.messagenum = messagenum;
		   },
		setChatList(state, item) {
		           state.chatList = item;
		       },
		 setChatItem(state, item) {
		            state.chatItem = item;
		        },
		 setToken(state, token) {
		      state.token = token;
		    },
		    setTokenCheckIntervalId(state, id) {
		      state.tokenCheckIntervalId = id;
		    },
		    clearTokenCheckInterval(state) {
		      if (state.tokenCheckIntervalId) {
		        clearInterval(state.tokenCheckIntervalId);
		        state.tokenCheckIntervalId = null;
		      }
		    },
		//相当于同步的操作
		handleChange(state, value) {
			websocketManager.init(`ws://${uploadurl.WS}?${value.id}`);
			state.followlist = value.followlist
			state.fanslist = value.fanslist
			state.id = value.id
			state.imageurl = value.image
			state.nickname = value.nickname
			state.fansnum = value.fansnum
			state.intro = value.intro
			state.username = value.username
			state.follownum = value.follownum
			state.concernnum = value.concernnum
		},
		quit(state){
			state.followlist = ''
			state.fanslist = ''
			state.id = ''
			state.followwarn = ''
			state.nickname = ''
			state.fansnum = ''
			state.intro = ''
			state.username = ''
			state.follownum = ''
			state.concernnum=''
			 state.token=''
		},
		getInfo(state){
			userinfo(state.id).then((value)=>{
				 state.followlist = value.data.followlist
				 state.fanslist = value.data.fanslist
				 state.id = value.data.id
				 state.imageurl = value.data.image
				 state.nickname = value.data.nickname
				 state.fansnum = value.data.fansnum
				 state.intro = value.data.intro
				 state.username = value.data.username
				 state.follownum = value.data.follownum
				 state.concernnum=value.data.concernnum
			})
		}
	},
	 getters: {
	    getToken: state => state.token,
	    getTokenCheckIntervalId: state => state.tokenCheckIntervalId,
	  },
	actions: {
		updateChatList({ commit }, item) {
		            commit('setChatList', item);
		        },
		updateChatItem({ commit }, item) {
		            commit('setChatItem', item);
		        },
		//相当于异步的操作,不能直接改变state的值，只能通过触发mutations的方法才能改变
		 updateToken({ commit }, token) {
		      commit('setToken', token);
		    },
		    startTokenCheck({ commit, state }) {
		      if (!state.tokenCheckIntervalId) {
		        const intervalId = setInterval(() => {
		          // 这里调用你的token验证逻辑
		          // 假设有一个方法叫做 checkTokenValidity
		          verifytoken(state.token).then((e)=>{
					  if(e.data.ret=='cuow'){
						    clearInterval(state.tokenCheckIntervalId);
						     state.tokenCheckIntervalId=0
							 const user = {
							    id: state.id,
							    username: state.username
							  };		
							  const data = {
							    user,
							    refreshToken: uni.getStorageSync('refreshToken')
							  };
						  Renewaltoken(data).then((e)=>{
							  if(e.code==200){
								  // 更新token成功
								   state.token = e.data.token;
								   uni.setStorageSync('refreshToken', e.data.refreshToken);
								   uni.setStorageSync('token', e.data.token);
								   store.dispatch('startTokenCheck')
							  }else{
								  // 刷新token失败，提醒用户登录失效，重新登录
								 uni.reLaunch({
								 	url: '/pages/index/index' // 注意路径格式  
								 });
								 store.dispatch('stopTokenCheck');
								 store.commit("quit")
								 state.tokenCheckIntervalId = null;
								 localStorage.removeItem('id')
								 uni.removeStorageSync('token')
								 uni.removeStorageSync('refreshToken')
							  }
						  })
					  }
				  })
		        }, 600000); // 每10分钟检查一次
		        commit('setTokenCheckIntervalId', intervalId);
		      }
		    },
		    stopTokenCheck({ commit }) {
		      commit('clearTokenCheckInterval');
		    },
	},
	modules: {

	},
	plugins: [
		// 可以有多个持久化实例  
		createPersistedState({
			key: 'app_config_data', // 状态保存到本地的 key   
			paths: ['imageurl', 'nickname', 'fansnum', 'intro', 'username',
			'follownum','id','followwarn','followlist','fanslist','concernnum','token','chatItem','chatList','messagenum'], // 要持久化的状态，在state里面取，如果有嵌套，可以  a.b.c 
			storage: { // 存储方式定义  
				getItem: (key) => uni.getStorageSync(key), // 获取  
				setItem: (key, value) => uni.setStorageSync(key, value), // 存储  
				removeItem: (key) => uni.removeStorageSync(key) // 删除  
			}
		})
	]
})
export default store